﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FTchina;
using System.Data;
using System.Collections;
using System.Text.RegularExpressions;
using ExtAspNet;
using FTchina.Library;
using FTchina.Logic;
using System.Text;

public partial class UI_menumanage : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {


        basic.CheckAdmin(this);
        basic.ChkPoewr(this, FTchina.Api.htmlpath.GetCurrentPagePath());


        if (!IsPostBack)
        {
            BtnMenuAct.Text = "确定添加";
            BindGrid();
        }

    }

    /// <summary>
    /// 绑定级别的下拉列表
    /// </summary>
    private void BindDropDownList()
    {
        DDLParentId.DataTextField = "Name";
        DDLParentId.DataValueField = "Id";
        DDLParentId.DataSimulateTreeLevelField = "Level";
        DDLParentId.DataEnableSelectField = "EnableSelect";
        DDLParentId.DataSource = MenuListLogic.getDropDownListTree();
        DDLParentId.DataBind();
        DDLParentId.Items.Add(new ExtAspNet.ListItem("根菜单", "RootMenu"));

        CkbPower.DataSource = shujuku.GetDataTable("select * from usergroup ");
        CkbPower.DataTextField = "groupname";
        CkbPower.DataValueField = "id";
        CkbPower.DataBind();
        CkbPower.SelectedValueArray = new string[] { "1" };//只有这样才能获取选择的项
    }


    /// <summary>
    /// 修改菜单项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnMenuAct_Click(object sender, EventArgs e)
    {

        if (TxbID.Text == DDLParentId.SelectedValue)
        {
            AlertLogic.ShowError("不能将自身作为父级菜单，请重新选择");
            return;
        }
        if (DDLParentId.SelectedValue == "RootMenu")
        {//根菜单类型
            if (BtnMenuAct.Text == "确定添加")
            {
                string RootItem = this.TxbConText.Text.Trim();
                AlertLogic.ShowResult(MenuListLogic.AddRootMenu(RootItem, 1));
            }
            else
            {
                string RootItem = this.TxbConText.Text.Trim();
                string MenuId = this.TxbID.Text.Trim();
                string Power = GetArrayString(CkbPower.SelectedValueArray);
                string Paixu = TxbPaixu.Text.Trim();
                AlertLogic.ShowResult(MenuListLogic.ModRootMenu(RootItem, MenuId, Power, Paixu));
            }
        }
        else
        {//普通菜单

            FTchina.Models.MenuList mMenuList = new FTchina.Models.MenuList();
            mMenuList.ConText = TxbConText.Text.Trim();
            mMenuList.Id = TxbID.Text.Trim() == "" ? 0 : Convert.ToInt32(TxbID.Text);
            mMenuList.ParentID = Convert.ToInt32(this.DDLParentId.SelectedValue);
            mMenuList.Power = GetArrayString(CkbPower.SelectedValueArray);
            mMenuList.Paixu = Convert.ToDecimal(TxbPaixu.Text.Trim());
            mMenuList.Link = TxbLink.Text.Trim();
            int x = 2;
            MenuListLogic.getTreeLevel(mMenuList.ParentID.ToString(), ref x);
            mMenuList.TreeLevel = x.ToString();
            AlertLogic.ShowResult(FTchina.BLL.MenuListManager.AddOrUpdateMenuList(mMenuList) > 0);
        }
        if (BtnMenuAct.Text == "确定修改")
        {
            //重新计算所有IDs的treeLevel
            MenuListLogic.setReferMenuIdsTreeLevel(TxbID.Text.Trim());
        }
        BindGrid();

    }


    /// <summary>
    /// 显示菜单
    /// </summary>
    /// <param name="ID"></param>
    protected void ShowMenuMod(string ID)
    {
        BtnMenuAct.Text = "确定修改";
        FTchina.Models.MenuList mMenuList = FTchina.BLL.MenuListManager.GetMenuListByid(Convert.ToInt32(ID));
        if (mMenuList != null)
        {
            if (MenuListLogic.IsRootItem(ID))
            {
                DDLParentId.SelectedValue = "RootMenu";
            }
            else
            {
                DDLParentId.SelectedValue = mMenuList.ParentID.ToString();
            }

            CkbPower.SelectedValueArray = mMenuList.Power.Split(',');
            TxbID.Text = mMenuList.Id.ToString();
            TxbConText.Text = mMenuList.ConText;
            TxbLink.Text = mMenuList.Link;
            TxbPaixu.Text = mMenuList.Paixu.ToString();
            TxbOldTreeLevel.Text = mMenuList.TreeLevel;//储存原始treelevel
        }
        else
        {
            AlertLogic.ShowResultAndRedirect("无数据！", "提示", HttpContext.Current.Request.Path.ToString(), false);
        }
    }

    /// <summary>
    /// 删除菜单及子菜单
    /// </summary>
    /// <param name="MenuId"></param>
    protected void DeleteMenuItem(string MenuId)
    {
       // basic.Log(MenuId);
        AlertLogic.ShowResult(MenuListLogic.DeleteMenuItem(MenuId));
        BindGrid();

    }
    protected void Grid1_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
    {
        object[] keys = Grid1.DataKeys[e.RowIndex];
        switch (e.CommandName)
        {
            case "ActionDel":
                {
                    DeleteMenuItem(keys[0].ToString());
                    break;
                }
            case "ActionEdit":
                {

                    ShowMenuMod(keys[0].ToString());
                    break;
                }
        }


        //String.Format("你点击了第 {0} 行，第 {1} 列，行命令是 {2}", e.RowIndex + 1, e.ColumnIndex + 1, e.CommandName);
        //String.Format("当前行数据 - 编号：{0}，姓名：{1}", keys[0], keys[1]);

    }



    #region 绑定列表
    private void BindGrid()
    {
        BindDropDownList();
        Grid1.DataSource = MenuListLogic.getTreeDataTable();
        Grid1.DataBind();
    }



    #endregion

    private string GetArrayString(string[] array)
    {
        StringBuilder sb = new StringBuilder();
        foreach (string item in array)
        {
            sb.Append(item);
            sb.Append(",");
        }
        return sb.ToString().TrimEnd(',');
    }






    /// <summary>
    /// 通过权限名称获取权限ID
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    protected String GetPowerIDByName(string name)
    {
        string sql = "select id from usergroup where groupname='" + name.Trim() + "'";
        //basic.Log(sql);
        return shujuku.GetDataTable(sql).Rows[0][0].ToString().Trim();
    }
    /// <summary>
    /// 通过权限ID获取权限名称
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    protected String GetPowerNameById(string id)
    {
        string sql = "select groupname from usergroup where id=" + id + "";
        // basic.Log(sql);
        return shujuku.GetDataTable(sql).Rows[0][0].ToString().Trim();
    }


    /// <summary>
    /// 通过ids 获取 powernames
    /// </summary>
    /// <param name="ids">1,2,3</param>
    /// <returns>系统管理员,普通用户,审核组</returns>
    protected String GetPowerNamesByIds(string ids)
    {
        string tmp = string.Empty;
        if (ids.Contains(","))
        {
            foreach (string str in ids.Split(','))
            {
                if (str.Trim().Length > 0)
                {
                    tmp += GetPowerNameById(str.Trim()) + ",";
                }
            }
        }
        else
        {
            if (ids.Trim().Length > 0)
            {
                tmp = GetPowerNameById(ids);
            }
        }
        if (tmp.EndsWith(","))
        {
            tmp = tmp.Substring(0, tmp.Length - 1);
        }

        return tmp;

    }
}
